﻿using SuperX.Common.AppConfiguration;
using SuperX.Common.Respository;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Text.RegularExpressions;

namespace SuperX.Common.Helper
{
    public class IPUtil
    {
        /// <summary>
        /// 获取当前设备IP4地址
        /// </summary>
        /// <returns></returns>
        public static string GetLocalIPV4()
        {
            string empty = string.Empty;
            List<IPAddress> source = (from ipAddress in Dns.GetHostEntry(Dns.GetHostName()).AddressList
                                      where ipAddress.AddressFamily == AddressFamily.InterNetwork
                                      select ipAddress into x
                                      orderby x.ToString()
                                      select x).ToList<IPAddress>();
            if (source.Count<IPAddress>() <= 0)
            {
                return "localhost";
            }
            return source.First<IPAddress>().ToString();
        }

        public static string GetLocalIP()
        {
            var cfg = SystemCfgService.GetInstance().SystemCfg;
            if (IsValid(cfg.IP))
                return cfg.IP;
            return GetLocalIPV4();
        }

        /// <summary>
        /// 获取当前设备所有IP4
        /// </summary>
        /// <returns></returns>
        public static IPAddress[] GetLocalIPV4s()
        {
            string empty = string.Empty;
            return (from ipAddress in Dns.GetHostEntry(Dns.GetHostName()).AddressList
                    where ipAddress.AddressFamily == AddressFamily.InterNetwork
                    select ipAddress).ToArray<IPAddress>();
        }

        //
        public static bool IsValid(object value)
        {
            string text = value as string;
            return text != null && !string.IsNullOrEmpty(text) && Regex.IsMatch(text, "^(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])\\.(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])\\.(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])\\.(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])$");
        }
    }
}